package com.cskaoyan.service.wx.impl;/*-*- coding = utf-8 -*-
@Time : 2022/11/22 15:24
@Author : 林涂兵
@File : WxSearchService.java
@Software: IntelliJ IDEA*/

import com.cskaoyan.bean.common.BaseParam;
import com.cskaoyan.bean.po.*;
import com.cskaoyan.bean.vo.wx.IndexSearchKeyword;
import com.cskaoyan.bean.vo.wx.SearchGoodsAndCategoryListVo;
import com.cskaoyan.mapper.MarketCategoryMapper;
import com.cskaoyan.mapper.MarketGoodsMapper;
import com.cskaoyan.mapper.MarketKeywordMapper;
import com.cskaoyan.mapper.MarketSearchHistoryMapper;
import com.cskaoyan.service.wx.WxSearchService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


@Service
public class WxSearchServiceImpl implements WxSearchService {
    @Autowired
    MarketKeywordMapper marketKeywordMapper;
    @Autowired
    MarketSearchHistoryMapper marketSearchHistoryMapper;
    @Autowired
    MarketGoodsMapper marketGoodsMapper;

    @Autowired
    MarketCategoryMapper marketCategoryMapper;

    /**
     * 获取关键词，热词等信息
     *
     * @return 封装好的类
     */
    public IndexSearchKeyword selectIndexKeyWord() {
        // 使用example进行查询 热词
        MarketKeywordExample example = new MarketKeywordExample();
        MarketKeywordExample.Criteria criteria = example.createCriteria();
        // 设置查询条件 ，条件为热词
        criteria.andIsHotEqualTo(true);
        // 获取返回的信息
        List<MarketKeyword> marketKeywords = marketKeywordMapper.selectByExample(example);

        // 设置返回值   默认关键字为 热词的第一个
        IndexSearchKeyword indexSearchKeyword = new IndexSearchKeyword();
        if (marketKeywords != null) {
            indexSearchKeyword.setDefaultKeyword(marketKeywords.get(0));
        }
        indexSearchKeyword.setHotKeywordList(marketKeywords);

        // 获取 登录用户信息 判断是否显示历史关键词
        Subject subject = SecurityUtils.getSubject();
        Object object = subject.getPrincipals();

        // 查询历史关键词
        if (object != null) {
            MarketUser primaryPrincipal = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();

            MarketSearchHistoryExample marketSearchHistoryExample = new MarketSearchHistoryExample();

            // 时间降序排列
            marketSearchHistoryExample.setOrderByClause("add_time desc");

            MarketSearchHistoryExample.Criteria criteria1 = marketSearchHistoryExample.createCriteria();
            // 查找当前用户的历史关键词
            criteria1.andUserIdEqualTo(primaryPrincipal.getId());

            List<MarketSearchHistory> marketSearchHistories = marketSearchHistoryMapper.selectByExample(marketSearchHistoryExample);
            indexSearchKeyword.setHistoryKeywordList(marketSearchHistories);
        }
        return indexSearchKeyword;
    }

    // 根据部分关键词找出对应的关键词词
    @Override
    public List<String> selectHotKeyword(String keyword) {
        // 使用逆向工程获取对应的数据
        MarketKeywordExample example = new MarketKeywordExample();
        example.createCriteria().andKeywordLike("%" + keyword.trim() + "%");
        List<MarketKeyword> marketKeywords = marketKeywordMapper.selectByExample(example);

        // 判空
        if (marketKeywords.size() == 0) {
            return null;
        }
        return marketKeywords.stream().map(a -> a.getKeyword()).collect(Collectors.toList());

    }

    // 存入对应用户的搜索关键词
    @Override
    public void insertHistoryKeyword(String keyword) {

        // 获取 登录用户信息 判断是否插入历史关键词
        Subject subject = SecurityUtils.getSubject();
        Object object = subject.getPrincipals();

        // 判断用户是否登录  根据用户id插入关键词
        if (object == null) {
            return;
        }

        MarketUser user = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();

        // 搜索数据库表中是否存在该关键词 ，不存在则插入，存在则更新 update_time
        // 查找其id
        Integer id  = marketSearchHistoryMapper.selectKeyword(keyword);

        // 创建对应的对象
        MarketSearchHistory historyKeyword = new MarketSearchHistory();
        historyKeyword.setUpdateTime(new Date());
        historyKeyword.setUserId(user.getId());

        // 存在
        if ( id != null){
            historyKeyword.setId(id);
            marketSearchHistoryMapper.updateByPrimaryKeySelective(historyKeyword);
            return;
        }
        historyKeyword.setAddTime(new Date());
        // 向数据库中插入历史搜索记录
        historyKeyword.setKeyword(keyword);
        marketSearchHistoryMapper.insertSelective(historyKeyword);
    }

    /*// 根据关键字搜索对应的商品，并分页
    @Override
    public SearchGoodsAndCategoryListVo selectGoodsByKeyword(BaseParam baseParam, String keyword, Integer categoryId, Integer brandId) {

        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        MarketGoodsExample.Criteria criteria1 = marketGoodsExample.createCriteria();
        MarketGoodsExample.Criteria criteria2 = marketGoodsExample.createCriteria();
        // 排序
        if (baseParam.getSort() != null) {
            marketGoodsExample.setOrderByClause(baseParam.getSort() + " " + baseParam.getOrder());
        }

        if (keyword == null && categoryId!=null&&categoryId != 0 && brandId == null) {
            SearchGoodsAndCategoryListVo categoryListVo = new SearchGoodsAndCategoryListVo();
            categoryListVo.setFilterCategoryList(null);
            // 开启分页
            PageHelper.startPage(baseParam.getPage(), baseParam.getLimit());
            // 根据接收到的类别id查询所有的商品;
            List<MarketGoods> goods = marketGoodsMapper.selectGoodsByCateId(categoryId);
            PageInfo<MarketGoods> info = new PageInfo<>(goods);
            List<MarketGoods> list = info.getList();
            int pageSize = info.getPageSize();
            int pages = info.getPages();
            int pageNum = info.getPageNum();
            long total = info.getTotal();
            categoryListVo.setLimit(pageSize);
            categoryListVo.setPages(pages);
            categoryListVo.setPage(pageNum);
            categoryListVo.setTotal(total);
            categoryListVo.setList(list);
            return categoryListVo;
        } else if (keyword==null&&categoryId==null&&brandId!=null){
            // 查询专题里的list
            SearchGoodsAndCategoryListVo categoryListVo=new SearchGoodsAndCategoryListVo();
            categoryListVo.setFilterCategoryList(null);
            // 开启分页
            PageHelper.startPage(baseParam.getPage(), baseParam.getLimit());
            // 根据接收到的类别id查询所有的商品;
            List<MarketGoods> goods = marketGoodsMapper.selectGoodsByBrandId(brandId);
            PageInfo<MarketGoods> info = new PageInfo<>(goods);
            List<MarketGoods> list = info.getList();
            int pageSize = info.getPageSize();
            int pages = info.getPages();
            int pageNum = info.getPageNum();
            long total = info.getTotal();
            categoryListVo.setLimit(pageSize);
            categoryListVo.setPages(pages);
            categoryListVo.setPage(pageNum);
            categoryListVo.setTotal(total);
            categoryListVo.setList(list);
            return categoryListVo;
        }

            if (StringUtils.isEmpty(keyword.trim())) {
                return null;
            }

        criteria1.andNameLike("%" + keyword.trim() + "%");
        if (categoryId != 0) {
            criteria1.andCategoryIdEqualTo(categoryId);
        }

        criteria2.andKeywordsLike("%" + keyword.trim() + "%");
        marketGoodsExample.or(criteria2);

        // 开启分页
        PageHelper.startPage(baseParam.getPage(), baseParam.getLimit());

        List<MarketGoods> goods = marketGoodsMapper.selectByExample(marketGoodsExample);

        SearchGoodsAndCategoryListVo searchGoodsAndCategoryList = new SearchGoodsAndCategoryListVo();
        searchGoodsAndCategoryList.setLimit(baseParam.getLimit());
        searchGoodsAndCategoryList.setPage(baseParam.getPage());

        if (goods == null || goods.size() == 0) {
            return searchGoodsAndCategoryList;
        }


        // 获取分页后的信息
        PageInfo<MarketGoods> marketGoodsPageInfo = new PageInfo<>(goods);
        int pages = marketGoodsPageInfo.getPages();
        long total = marketGoodsPageInfo.getTotal();

        searchGoodsAndCategoryList.setPages(pages);
        searchGoodsAndCategoryList.setTotal(total);

        Set<Integer> categories = goods.stream().map(a -> a.getCategoryId()).collect(Collectors.toSet());

        // 查找商品类目集合
        ArrayList<MarketCategory> marketCategories = new ArrayList<>();
        for (Integer category : categories) {
            MarketCategory marketCategory = marketCategoryMapper.selectByPrimaryKey(category);
            marketCategories.add(marketCategory);
        }
        searchGoodsAndCategoryList.setFilterCategoryList(marketCategories);
        searchGoodsAndCategoryList.setList(goods);
        return searchGoodsAndCategoryList;

    }*/

    // 根据session中的userId删除对应的历史搜索关键词
    @Override
    public void deleteAllHistoryKeywordByUserId() {
        // 获取当前用户
        Subject subject = SecurityUtils.getSubject();
        MarketUser user = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();

        // 删除对应user的历史记录
        MarketSearchHistoryExample marketSearchHistoryExample = new MarketSearchHistoryExample();
        MarketSearchHistoryExample.Criteria criteria = marketSearchHistoryExample.createCriteria();
        criteria.andUserIdEqualTo(user.getId());

        marketSearchHistoryMapper.deleteByExample(marketSearchHistoryExample);
    }
}
